package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径,判断是否是登录请求
        String path = request.getURI().getPath();
        if (path.contains("login_auth")) {
            // 是登录请求,放行
            return chain.filter(exchange);
        }

        // 如果不是登录请求,判断请求头中是否携带token信息
        // 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        // 如果token为空
        if (StringUtils.isEmpty(token)) {
            // 返回未授权状态码,并终止请求
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            // 如果token不为空,判断token是否失效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //是否是过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                // token已失效,返回未授权状态码,并终止请求
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            // 通过token获取当前登录用户的id,添加到请求头中
            String userId = claimsBody.get("id").toString();
            // 对request请求做一个增强,添加一个用户id的键值对
            ServerHttpRequest httpRequest = request
                    .mutate()
                    .headers(httpHeaders -> httpHeaders.add("userId", userId + "")).build();
            // 替换旧的request对象
            exchange.mutate().request(httpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 放行
        return chain.filter(exchange);
    }
}
